package me.send.business.service.service;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.send.business.base.BaseSMS;
import me.send.business.base.ErrorEntity;
import me.send.business.base.SendVariable;
import me.send.business.base.openAccount.AccountOperate;
import me.send.business.service.BaseService;
import me.send.business.service.bean.UserEvaluateInfoBean;
import me.send.business.service.bean.UserInfoBean;
import me.send.business.service.cons.MessageCons;
import me.send.business.service.mapper.BalanceMapper;
import me.send.business.service.mapper.RedMapper;
import me.send.business.service.mapper.UserMapper;
import me.send.business.service.mapper.UserredMapper;
import me.send.business.service.pojo.Balance;
import me.send.business.service.pojo.Message;
import me.send.business.service.pojo.Red;
import me.send.business.service.pojo.User;
import me.send.business.service.pojo.Userred;
import me.send.framework.util.CacheUtil;
import me.send.framework.util.HelperUtil;
import me.send.framework.util.MD5Util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserService extends BaseService {

	// 呼送验证码：XXXX。（3分钟有效）【呼送科技】
	// MTUyNjE4ODczOTU= 15261887395 base64加密后

	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private BalanceMapper balanceMapper;

	// 定义一个code变量 保存的时间是3分钟 2015年5月27日10:17:33

	@Autowired
	private RedMapper redMapper;

	@Autowired
	private UserredMapper userredMapper;
	
	// 测试接口
	public List<Map<String, Object>> list_all(){
		return userMapper.list_all();
	}
	

	// 修改头像 2015年6月4日09:21:22
	public Map<String, Object> update_header(String devicenumber, String headerpath,
			int userid) {
		Map<String, Object> map = new HashMap<String, Object>();
		ErrorEntity entity = error_1002();
		Map<String, Object> userMap = new HashMap<String, Object>();
		if (isDevicenumber(devicenumber)) {
			if (userid != 0) {
				// 调用update_header方法
				User user = new User();
				// 设置这个对象下面的属性
				user.setUpdatetime(HelperUtil.getCurrentDate());
				user.setHeaderpath(headerpath);
				user.setUserid(userid);
				// 调用更新方法
				try {
					userMapper.update_header(user);
					userMap = userMapper.refresh(userid);
					entity = error_1000();
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				entity = error_1006();
			}
		} else {
			entity = error_1002();
		}
		
		map.put(SendVariable.COMM_ERROR, entity);
		map.put(SendVariable.COMMON_OBJECT, userMap);
		return map;
	}

	// 修改用户信息 2015年6月4日09:29:37
	public ErrorEntity update_user(String devicenumber, User user) {
		if (isDevicenumber(devicenumber)) {
			if (user != null) {
				user.setUpdatetime(HelperUtil.getCurrentDate());
				try {
					userMapper.update_user(user);
					return error_1000();
				} catch (Exception e) {
					e.printStackTrace();
					return error_1001();
				}
			} else {
				return error_1006();
			}
		} else {
			return error_1002();
		}

	}

	/**
	 * 用户修改密码
	 */
	public ErrorEntity updatePassword(String telephone, String devicenumber,
			String code, String password) {
		if (isDevicenumber(devicenumber)) {
			if (telephone != null && !telephone.equals("") && password != null
					&& !"".equals(password)) {
				// 调用相关的短信接口
				// telephone = Base64Util.getFromBase64(telephone);
				// 判断验证码
				CacheUtil cacheUtil = CacheUtil.getInstance();
				if (cacheUtil.get(telephone) == null) {
					return error_1004();
				}

				if (!cacheUtil.get(telephone)
						.equals(code)) {
					return error_1005();
				}
				User user = new User();
				user.setUpdatetime(HelperUtil.getCurrentDate());
				user.setTelephone(telephone);
				user.setPassword(password);
				userMapper.updatePassword(user);
				return error_1000();
			} else {
				return error_1001();
			}
		} else {
			return error_1002();
		}
	}

	/**
	 * 根据手机号码 获取到验证码
	 * 
	 * 2015年5月27日10:16:21
	 */
	public Map<String, Object> sendCode(String telephone, String devicenumber) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put(SendVariable.COMM_ERROR, error_1001());
		if (!isDevicenumber(devicenumber)) {
			map.put(SendVariable.COMM_ERROR, error_1002());
		} else {
			if (telephone != null && !telephone.equals("")) {
				// 调用相关的短信接口
				// telephone = Base64Util.getFromBase64(telephone);
				int x = (int) (Math.random() * 9000 + 1000);
				// map.put(SystemVariable.COMM_CODE, x);
				//BaseSMS.getMessage(telephone, x + "");
				// 赋值开始时间 2015年5月27日10:57:16
//				Date regDate = new Date(180 * 1000);
				// map.put(SystemVariable.COMM_CODE, x);
				BaseSMS.getMessage(telephone, x + "");
				
//				CacheHelper.replace(telephone, x + "",
//						regDate);
				CacheUtil cacheUtil = CacheUtil.getInstance();
				cacheUtil.set(telephone, 180,  x + "");
				map.put("error", error_1000());
			}
		}
		return map;
	}

	/**
	 * 验证手机号码是否可以注册
	 */
	public ErrorEntity verification(String telephone, String devicenumber) {
		if (isDevicenumber(devicenumber)) {
			if (userMapper.count_telephone(telephone) > 0) {
				return error_1003();
			}
			return error_1000();
		}
		return error_1002();
	}

	/**
	 * 用户登录
	 */
	public Map<String, Object> login(User user, String devicenumber) {
		Map<String, Object> map = new HashMap<String, Object>();
		ErrorEntity entity = error_1001();
		map.put(SendVariable.COMMON_OBJECT, new User());
		if (isDevicenumber(devicenumber)) {
			// 判断手机号码或者是密码是null 2015年6月1日15:37:57
			if (user != null && user.getPassword() != null
					&& user.getTelephone() != null) {
				User user2 = userMapper.login(user);
				if (user2 != null && user2.getUserid() != 0) {
					entity = error_1000();
					map.put(SendVariable.COMMON_OBJECT, user2);
				} else {
					entity = error_1007();
				}
			}
		}
		map.put(SendVariable.COMM_ERROR, entity);
		return map;
	}

	/**
	 * 用户注册
	 */
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = { Exception.class })
	public ErrorEntity register(String telephone, String devicenumber,
			String code, String password) {
		try {
			if (isDevicenumber(devicenumber)) {
				// 调用相关的短信接口
				// telephone = Base64Util.getFromBase64(telephone);
				// 判断验证码
				if ((telephone != null) && (!telephone.equals(""))
						&& (password != null) && (!"".equals(password))) {
					// 调用相关的短信接口
					// telephone = Base64Util.getFromBase64(telephone);
					// 判断验证码
					
					//验证是否注册过
					CacheUtil cacheUtil = CacheUtil.getInstance();
					if (cacheUtil.get(telephone) == null) {
						return error_1004();
					}

					if (!cacheUtil.get(telephone)
							.equals(code)) {
						return error_1005();
					}

					User user = new User();
					user.setCreatetime(HelperUtil.getCurrentDate());
					// 使用uuid的10位 做用户名
					user.setNickname(telephone.substring(1, 6)
							+ HelperUtil.uuid().substring(0, 5));
					// 设置 电话号码 密码 最后注册
					user.setTelephone(telephone);
					user.setPassword(password);
					//注册阿里云帐号
					AccountOperate operate = new AccountOperate();
					String id = MD5Util.MD5(devicenumber
							+ System.currentTimeMillis()+Math.random());
					System.out.println("broker id is :" + id);
					Long openAccountId = operate.createBrokerAccount(id + "");
					System.out.println("openAccountId:" + openAccountId);
					if (openAccountId == null) {
						System.out.println("注册阿里百川云账号失败");
					} else {
						user.setOpenAccountId(openAccountId);
						System.out.println("注册阿里百川云账号成功");
					}
					user.setIsvAccountId(id);
					
					this.userMapper.register(user);

					Userred userred = new Userred();
					userred.setCreatetime(HelperUtil.getCurrentDate());

					Red red = redMapper.limit_one_red();

					if (red!=null) {
						userred.setRedid(red.getRedid());
						userred.setRednumber(red.getRednumber());
						userred.setStatus("1");
						userred.setUserid(userMapper
								.userid_user_telephone(telephone));

						String format_ = "yyyy-MM-dd";

						String start = HelperUtil.getCurrentDate(format_);

						Date date = new Date();

						Calendar calendar = Calendar.getInstance();
						calendar.setTime(date);
						calendar.add(Calendar.DAY_OF_MONTH,10);//红包可用时间10天
						Date endDate = calendar.getTime();
						String end = HelperUtil.getDateValue(format_, endDate);
						System.out.println("start"+start);
						System.out.println("end"+end);
						userred.setStarttime(start + " 00:00:00");
						userred.setEndtime(end + " 23:59:59");
							
						userred.setTypeid(1);

						userredMapper.save(userred);
						Message message = new Message("成功注册，系统为您送出一个红包，赶快使用吧！", userred.getUserid(), MessageCons.USER_TYPE_USER, MessageCons.MESSAGE_TYPE_ORDER);
						saveMessage(message);
						red.setUpdatetime(HelperUtil.getCurrentDate());
						red.setStatus(2);
						redMapper.update_status_redid(red);
					}
					
					return error_1000();
				}
				return error_1001();
			}

			return error_1002();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException();
		}

	}

	/**
	 * 刷新用户 更新用户编号 查询用户对象
	 */
	public Map<String, Object> refresh(String devicenumber, int userid) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put(SendVariable.COMM_ERROR, error_1001());
		Map<String, Object> map2 = new HashMap<String, Object>();
		if (isDevicenumber(devicenumber)) {
			// 查询单个对象
			map2 = userMapper.refresh(userid);
			String telephone ="";
			if (map2.get("telephone")!=null) {
				telephone = map2.get("telephone").toString();
			}
			Integer account = 0;
			// 查询出用户的余额 2015年7月20日14:06:06
			// 判断是否有账户
			int isFlag = balanceMapper.count_userid(userid);
			if (isFlag>0) {
				account = Integer.parseInt(balanceMapper.balance_userid(userid).get("account").toString());
			}else {
				Balance balance = new Balance();
//				balance.setAccount("0");
				balance.setCreatetime(HelperUtil.getCurrentDate());
				balance.setUserid(userid);
				balance.setDescption("初始化账号,账号名称:"+userid);
				balance.setTelephone(telephone);
				// (#{createtime},#{userid},#{descption},#{telephone})
				balanceMapper.save(balance);
			}
			map2.put("account", account==null?0:account.intValue());
			map.put(SendVariable.COMM_ERROR, error_1000());
		} else {
			map.put(SendVariable.COMM_ERROR, error_1002());
		}
		map.put(SendVariable.COMMON_OBJECT, map2);
		return map;
	}

	public List<UserEvaluateInfoBean> getEvaluates(int orderid){
		return userMapper.getEvaluates(orderid);
	}
	
	public UserInfoBean getUserByOrderId(int orderid){
		return userMapper.getUserByOrderId(orderid);
	}
}